package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService{

    //关联mapper
    @Autowired
    private TravelMapper travelMapper;
    //关联mapper
    @Autowired
    private TravelContentMapper travelContentMapper;


    @Override
    public PageInfo<Travel> queryForList(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderby());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo<Travel>(list);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
                //获取当前时间
                Date date = new Date();
                //获取游记内容对象
                TravelContent travelContent = travel.getTravelContent();

            if(travel.getId()==null){
                //新增操作,自动设置创建时间和最后更新时间,这俩时间一样的
                travel.setCreateTime(date);
                travel.setLastUpdateTime(date);
                //先保存travel表,再获取id保存游记内容
                travelMapper.insert(travel);
                //获取travel里的游记对象,此时里面只有内容,没有id,把travle的id设置进去
                travelContent.setId(travel.getId());
                travelContentMapper.insert(travelContent);
            }else{
                //编辑操作
                //设置最后更新时间
                travel.setLastUpdateTime(date);
                travelMapper.updateByPrimaryKey(travel);
                //更新游记内容
                travelContent.setId(travel.getId());
                travelContentMapper.updateByPrimaryKey(travelContent);
            }
    }

    @Override
    public Travel getById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public TravelContent getContentById(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void changeState(Travel travel) {
        //这里完善一下执行修改语句需要的信息,多加一个发布时间
        //如果该文章要发布,需要修改发布时间
        if(travel.getState()==Travel.STATE_RELEASE){
        travel.setReleaseTime(new Date());
        }
        //修改状态
        travelMapper.changeState(travel);


    }
}
